package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.INcInputMilkService;
import com.ruoyi.system.service.INcOrderCfService;
import com.ruoyi.system.service.INcOutputMilkService;
import com.ruoyi.system.util.ExcelUtil2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 牛奶出库 信息操作处理
 *
 * @author ruoyi
 * @date 2019-09-11
 */
@Controller
@RequestMapping("/system/ncOutputMilk")
public class NcOutputMilkController extends BaseController {
    private String prefix = "system/ncOutputMilk";
    private String cowPrefix="system/screen";
    @Autowired
    private INcOutputMilkService ncOutputMilkService;

    @Autowired
    private INcOrderCfService ncordercfser;

    @Autowired
    private INcInputMilkService ncInputMilkService;

    @Autowired
    private INcOrderCfService orderCfService;

    @RequiresPermissions("system:ncOutputMilk:view")
    @GetMapping()
    public String ncOutputMilk() {
        return prefix + "/ncOutputMilk";
    }


    @GetMapping("/ncOutputMilkAll")
    public String ncOutputMilkAll() {
        return prefix + "/ncOutputMilk-all";
    }

    /**
     * 查询牛奶出库列表
     */
    @RequiresPermissions("system:ncOutputMilk:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcOutputMilk ncOutputMilk) {
        startPage();
        List<NcOutputMilk> list = ncOutputMilkService.selectNcOutputMilkList(ncOutputMilk);
        return getDataTable(list);
    }

    /**
     * 查询牛奶出库列表
     */
    @PostMapping("/listTodays")
    @ResponseBody
    public TableDataInfo listTodays(NcOutputMilk ncOutputMilk,String today,Integer type) {
        startPage();
        ncOutputMilk.getParams().put("today", today);
        ncOutputMilk.getParams().put("type", type);
        List<NcOutputMilk> list = ncOutputMilkService.selectNcOutputMilkList(ncOutputMilk);
        return getDataTable(list);
    }


    /**
     * 导出牛奶出库列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcOutputMilk ncOutputMilk) {
        List<NcOutputMilk> list = ncOutputMilkService.selectNcOutputMilkList(ncOutputMilk);
//        ExcelUtil<NcOutputMilk> util = new ExcelUtil<NcOutputMilk>(NcOutputMilk.class);
        ExcelUtil2<NcOutputMilk> util = new ExcelUtil2<>(NcOutputMilk.class);
        return util.exportExcel(list, "牛奶出库单");
    }

    /**
     * 新增牛奶出库
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存牛奶出库
     */
    @RequiresPermissions("system:ncOutputMilk:add")
    @Log(title = "牛奶出库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcOutputMilk ncOutputMilk) {
        ncOutputMilk.setOutputType(2);
        return toAjax(ncOutputMilkService.insertNcOutputMilk(ncOutputMilk));
    }

    /**
     * 修改牛奶出库
     */
    @GetMapping("/edit/{outputId}")
    public String edit(@PathVariable("outputId") Long outputId, ModelMap mmap) {
        NcOutputMilk ncOutputMilk = ncOutputMilkService.selectNcOutputMilkById(outputId);

        if (ncOutputMilk.getCforderId() != null) {
            NcOrderCf ncOrderCf = orderCfService.selectNcOrderCfById(Long.valueOf(ncOutputMilk.getCforderId()));
            ncOutputMilk.setCforderCode(ncOrderCf.getCforderCode());//编号
            ncOutputMilk.setRequestAmount(ncOrderCf.getRequestAmount());
			/*ncOutputMilk.setCropNameCn(ncOrderCf.getCropNameCn());
			ncOutputMilk.setCropVarieties(ncOrderCf.getCropVarieties());
			ncOutputMilk.setCropVarietiesCn(ncOrderCf.getCropVarietiesCn());*/

        }


        mmap.put("ncOutputMilk", ncOutputMilk);
        return prefix + "/edit";
    }

    /**
     * 修改保存牛奶出库
     */
    @RequiresPermissions("system:ncOutputMilk:edit")
    @Log(title = "牛奶出库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcOutputMilk ncOutputMilk) {
		/*//修改种类名称
		NcOrderCf ncOrderCf = orderCfService.selectNcOrderCfById(Long.valueOf(ncOutputMilk.getCforderId()));
		ncOrderCf.setCropVarieties(ncOutputMilk.getCropVarieties());
		ncOrderCf.setCropVarietiesCn(ncOutputMilk.getCropVarietiesCn());
		orderCfService.updateNcOrderCf(ncOrderCf);*/
        NcOrderCf ncOrderCf = new NcOrderCf();
        ncOrderCf.setRequestAmount(ncOutputMilk.getRequestAmount());
        ncOrderCf.setCforderId(Long.valueOf(ncOutputMilk.getCforderId()));
        orderCfService.updateNcOrderCf(ncOrderCf);
        return toAjax(ncOutputMilkService.updateNcOutputMilk(ncOutputMilk));
    }

    /**
     * 删除牛奶出库
     */
    @RequiresPermissions("system:ncOutputMilk:remove")
    @Log(title = "牛奶出库", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncOutputMilkService.deleteNcOutputMilkByIds(ids));
    }

    /**
     * 确认生成出库
     */
    @Log(title = "确认生成出库单", businessType = BusinessType.OTHER)
    @PostMapping("/confirmTable")
    @ResponseBody
    public AjaxResult confirmTable(String ids) {
        SysUser user = ShiroUtils.getSysUser();
        return toAjax(ncOutputMilkService.createOrderByIds(ids, user));
    }

    /**
     * 确认
     * outputAmount   outputTime outputUser    remark
     */
    @GetMapping("/enter/{id}")
    public String enter(@PathVariable("id") long cforderId, ModelMap map) {
        NcOrderCf ncOrderCf = ncordercfser.selectNcOrderCfById(cforderId);

//		NcOutputMilk ncOutputMilk = ncOutputMilkService.selectNcOutputMilkById(cforderId);
        NcOutputMilk OutputMilk = new NcOutputMilk();

        OutputMilk.setOutputId(cforderId);

        NcInputMilk ncInputMilk = new NcInputMilk();
        ncInputMilk.getParams().put("stock", 1);

        List<NcInputMilk> stocks = ncInputMilkService.selectNcInputMilkList(ncInputMilk);
        map.put("milk", OutputMilk);
        map.put("cforderId", cforderId);
        map.put("ncOrderCf", ncOrderCf);
        map.put("stocks", stocks);
        return prefix + "/enter";

    }

    /**
     * 新增保存牛奶出库工作记录
     */
    @RequiresPermissions("system:ncOutputChicken:addWork")
    @Log(title = "牛奶出库", businessType = BusinessType.UPDATE)
    @PostMapping("/addWork")
    @ResponseBody
    public AjaxResult addWork(NcOutputMilk ncOutputMilk) {

        NcInputMilk ncInputMilk = ncInputMilkService.selectNcInputMilkById(Integer.parseInt(ncOutputMilk.getInputId() + ""));
//		if (ncInputMilk.getLeftAmout() !=null) {
//				if ((Integer.parseInt(ncInputMilk.getLeftAmout()+""))>=(Integer.parseInt(ncOutputMilk.getOutputAmout()+"")) ) {
        if (ncInputMilk.getLeftAmout().compareTo(ncOutputMilk.getOutputAmout()) > -1) {

            ncOutputMilk.setOutputType(2);
            NcOrderCf ncOrderCf = new NcOrderCf();
            ncOrderCf.setCforderStatus("8");
            ncOrderCf.setCforderId(ncOutputMilk.getNcorderCfId());
            ncordercfser.updateNcOrderCf(ncOrderCf);
            //ncOutputMilk.setMilkCode(NcUtils.getMilkCode()+ncOutputMilk.getOutputUser());//牛奶批次
            ncOutputMilk.setCforderId(Integer.parseInt(ncOutputMilk.getNcorderCfId() + ""));

            //减少牛奶库存
//				int amout = (Integer.parseInt(ncInputMilk.getLeftAmout()+""))-(Integer.parseInt(ncOutputMilk.getOutputAmout()+""));
            BigDecimal amount = ncInputMilk.getLeftAmout().subtract(ncOutputMilk.getOutputAmout());
            ncInputMilk.setLeftAmout(amount);
            ncInputMilkService.updateNcInputMilk(ncInputMilk);//更新库存
            return toAjax(ncOutputMilkService.insertNcOutputMilk(ncOutputMilk));
        }
        return AjaxResult.error("库存不足");
    }
//		return AjaxResult.error("库存为空");
    /**
     牛舍大屏产奶量
     */
    @GetMapping("/niushe1")
    public String feedAmounts(ModelMap map) {
        Calendar cal = Calendar.getInstance();
        //获取最近7天的数据
        List<Double> cowAamount = new ArrayList<Double>();
        NcOutputMilk cow = new NcOutputMilk();
        cow.setOutputType(3);
        String[] last7Day = last7Day(cal);
        for (int i = 0; i < last7Day.length; i++) {
            cow.getParams().put("day", last7Day[i]);
            double amount = ncOutputMilkService.selectNcCowsMilkScreen(cow);
            cowAamount.add(amount);
        }
        map.put("cow", cowAamount);
        map.put("date", last7Day);
        //今天以及昨天同比
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String time2 = format2.format(Calendar.getInstance().getTime());
        cow.getParams().put("day", time2);
        double todayAmount = ncOutputMilkService.selectNcCowsMilkScreen(cow);
        map.put("todayAmount", todayAmount);
        //获取昨天
        NcOutputMilk cow1 = new NcOutputMilk();
        cow1.setOutputType(3);
        Calendar cal1=Calendar.getInstance();
        cal1.add(Calendar.DATE, -1);
        String yesterday = format2.format(cal1.getTime());
        cow1.getParams().put("day", yesterday);
        double yesterdayAmount =ncOutputMilkService.selectNcCowsMilkScreen(cow1);
        if(yesterdayAmount != 0){
            map.put("dayRatio", new DecimalFormat("0.00").format(Double.valueOf((todayAmount - yesterdayAmount) / yesterdayAmount * 100)));
        }
        else{
            map.put("dayRatio",new DecimalFormat("0.00").format((double)Math.round(todayAmount*100)));

        }
        //本月以及上个月同比
        NcOutputMilk cow2 = new NcOutputMilk();
        cow2.setOutputType(3);
        Calendar cal2=Calendar.getInstance();
        String month = null;
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            month = cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        }
        else {
            month = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }
        cow2.getParams().put("month", month);
        double monthAmount = ncOutputMilkService.selectNcCowsMilkScreen(cow2);
        //上个月
        String lastMonth = null;
        cal2.add(Calendar.MONTH,-1);
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            lastMonth = cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        } else {
            lastMonth = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }
        cow2.getParams().put("month", lastMonth);
        double laMonth = ncOutputMilkService.selectNcCowsMilkScreen(cow2);
        map.put("month", monthAmount);
        if(laMonth != 0){
            map.put("monthRatio", new DecimalFormat("0.00").format(Double.valueOf((monthAmount - laMonth) / laMonth * 100)));
        }
        else{
            map.put("monthRatio", new DecimalFormat("0.00").format((double)Math.round(monthAmount*100)));
        }
        //本年以及去年月同比
        NcOutputMilk cow3 = new NcOutputMilk();
        cow3.setOutputType(3);
        String year = cal2.get(Calendar.YEAR) + "";
        cow3.getParams().put("year", year);
        double thisYear = ncOutputMilkService.selectNcCowsMilkScreen(cow3);
        cal2.add(Calendar.YEAR,-1);
        String year1 = cal2.get(Calendar.YEAR) + "";
        cow3.getParams().put("year", year1);
        double lastYear = ncOutputMilkService.selectNcCowsMilkScreen(cow3);
        map.put("year", thisYear);
        if(lastYear != 0){
            map.put("yearRatio", new DecimalFormat("0.00").format(Double.valueOf((thisYear - lastYear) / lastYear * 100)));
        }
        else{
            map.put("yearRatio", new DecimalFormat("0.00").format((double)Math.round(thisYear*100)));
        }
        return cowPrefix+"/cowMilk";
    }
    //产生最近一周的时间
    public String[] last7Day(Calendar cal) {
        String[] last7Day = new String[7];
        for (int i = 0; i < 7; i++) {
            if (cal.get(Calendar.MONTH) + 1 < 10) {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }
            } else {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[6 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }

            }
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1); //逐次往前推1天*/

        }
        return last7Day;
    }



}


